package com.shangyueshang.utils;

import org.springframework.beans.BeanUtils;

import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author Deycoesr@gmail.com
 * @since Fri 19/11/2021
 */
public abstract class FunctionUtil {

    private static final BiFunction<?, ?, ?> JUST_RETURN_SECOND = (first, second) -> second;

    @SuppressWarnings("unchecked")
    public static <First, Second> BiFunction<First, Second, Second> justReturnSecond() {
        return (BiFunction<First, Second, Second>) JUST_RETURN_SECOND;
    }

    public static <Source, Target> Function<Source, Target> beanCopy(Supplier<Target> targetSupplier) {
        return beanCopy(targetSupplier, justReturnSecond());
    }

    public static <Source, Target> Function<Source, Target> beanCopy(
            Supplier<Target> targetSupplier,
            BiFunction<Source, Target, Target> copiedThen
    ) {
        return source -> {
            if (Objects.isNull(source)) return null;
            Target target = targetSupplier.get();
            BeanUtils.copyProperties(source, target);
            return copiedThen.apply(source, target);
        };
    }

    public static <T, R> Function<T, R> cast(Function<T, R> function) {
        return function;
    }

}
